var http 	= require("http"),
	url		= require("url"),
	fs		= require("fs"),
	libxml 	= require("../core/support/libxmljs"),
	_		= require("../core/lib/underscore")._;

var host = "pike.ida.liu.se";
var page = "/development/pikefarm/7.8.xml"
var port = 80;


// TODO Clean up


var sys = require("sys");


function get(host, port, page, fn) {
	var client = http.createClient(port, host);
	var request = client.request('GET', page, {'host': host});
	request.end();
	request.addListener('response', function (response) {
		if (response.statusCode === 200) {
			var data = "";
			response.setEncoding('utf8');
			response.addListener('data', function (chunk) {
				data += chunk;
			});
			response.addListener('end', function () {
				fn(data);
			});
		}
	}); 
}

function getBenchmark(build) {
	var base = "/generated/pikefarm/7.8/";
	var id = build.query.id;
	var page = base + id + "/" + "benchmark.txt";

	var dir = process.cwd() + "/site/data/" + id + "/";
	var path = process.cwd() + "/site/data/" + id + "/" + "benchmark.txt";
	fs.stat(path, function (err, stat) {
		if (err) {
			sys.log("Get " + page);
			get(host, port, page, function (data) {
				fs.mkdir(dir, 0666, function (err) {
					fs.writeFile(path, data, function (err) {
					});
				});
			});
		} else {
			sys.log("Skip " + page);
		}
	});
}

function getBenchmarks(builds) {
	for (var i = 0; i < builds.length; i++) {
		getBenchmark(builds[i]);
	}
}

function scrubPage(fn) {
	get(host, port, page, function (data) {
		var doc = libxml.parseHtmlString(data);
		process.nextTick(function () {
			var links = doc.find("//a[@href]");
			var builds = [];
			for (link in links) {
				var attr = links[link].attr("href");
				if (attr && attr.value) {
					var url_parts = url.parse(attr.value(), true);
				 	if (url_parts.pathname === "result.xml") {
				 		builds.push(url_parts);
				 	}
				 }			 	
			}
			fn(builds);
		});
	});
}

// Ugly!
function parseBenchmark(path, id, fn) {
	fs.readFile(path, function (err, data) {
		if (err) {
			return console.log("ERROR");
		}
		var rows = [];
		var s = data.toString("utf8");
		// Ugly
		var pos = s.indexOf("/buildtmp/");
		var host = s.slice(s.slice(0, pos).lastIndexOf("/") + 1, pos);
		
		var test = s.indexOf("test   ");
		if (test === -1) {
			return;
		}
		s = s.slice(test);
		var a = s.split("\n");

		var match = a[0].match(/(test)( +)/);
		if (!match) {
			return;
		}	
		var columns = [];
		columns.push(match[1]);
		a[0] = a[0].slice(match[0].length);
		columns = columns.concat(_.compact(a[0].split(" ")));;
		columns.push("(runs/s)");
		for (var i = 1; i < a.length - 1; i++) {
			var row = []
			row.push(a[i].slice(0, match[0].length));
			if (row[0].indexOf("find_lib_dir...") !== -1) {
				return;
			}
			row = row.concat(_.compact(a[i].slice(match[0].length).split(" ")));
			var s1 = row.pop();
			var s2 = row.pop();
			if (_.isUndefined(s2)) {
				continue;
			}
			if (s1[0] === "(" ) {
				row.push(s2);
				row.push(s1);
			} else {
				row.push(s2.concat(" ", s1));	
			}
			rows.push(row);
		}		
		fn({ host: host,
			 columns: columns,
			 rows: rows,
			 id: id });
	});
}

var mem = {};

function parseBenchmarks() {
	var data = process.cwd() + "/" + "site/data/";
	fs.readdir(data, function (err, dirs) {
		for (var i = 0; i < dirs.length; i++) {
			parseBenchmark(data + dirs[i] + "/benchmark.txt", dirs[i],  function (result) {
					if (!mem[result.host]) {
						mem[result.host] = {};
						mem[result.host].ids = [];
						mem[result.host].res = [];
					}
					mem[result.host].res.push(result);
					mem[result.host].ids.push(result.id);
					sys.log("Adding one more benchmark to " + result.host);
				
			});
		}
	});
}

var show = "welcome.linkeo.intra";


exports.getData = function () {
	if (mem[show]) {
		return mem[show];
	} else {
		return null;			
	}
}

exports.site = function () {
	scrubPage(getBenchmarks);
	parseBenchmarks(); // TODO fix directory listener
};
